/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_guestbook.htm
 *
 * Zhiqim Guestbook is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.example.gbook.action;

import org.zhiqim.example.gbook.dbo.Message;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.GetPostAction;
import org.zhiqim.httpd.util.Sessions;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNumericLen;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.orm.ORM;

/**
 * 访客留言
 *
 * @version v1.0.0 @author zouzhigang 2016-9-1 新建与整理
 * @version v1.0.1 @author zouzhigang 2017-3-10 
 *      1)修改validateCode为verificationCode
 *      2)修改messageId为long型
 *      3)增加对内容的formatHtml
 */
public class LeaveMessageAction extends GetPostAction
{
    @Override
    protected void validate(HttpRequest request)
    {//留言页面和处理验证
        request.addValidate(new IsLen("messageName", "称呼不能为空且不超过16个字符", 1, 16));
        request.addValidate(new IsLen("messageContacting", "联系方式不超过25个字符", 0, 25));
        request.addValidate(new IsLen("messageContent", "留言内容不能为空且不超过500字符", 1, 500));
        request.addValidate(new IsNumericLen("verificationCode", "验证码必须是4位数字", 4, 4));
    }
    
    @Override
    protected void doGet(HttpRequest request) throws Exception
    {//留言页面
    }

    @Override
    protected void doPost(HttpRequest request) throws Exception
    {//留言处理
        String verificationCode = request.getParameter("verificationCode");
        String vcode = Sessions.getSessionVerificationCode(request);
        if (!verificationCode.equals(vcode))
        {
            request.returnHistory("验证码不正确或已失效，请新输入！");
            return;
        }
        
        String messageName = request.getParameter("messageName");
        String messageContacting = request.getParameter("messageContacting");
        String messageContent = request.getParameter("messageContent");
        
        //插入到数据库
        Message message = new Message();
        message.setMessageId(Ids.longId());
        message.setMessageName(messageName);
        message.setMessageContacting(messageContacting);
        message.setMessageContent(messageContent);
        message.setMessageTime(DateTimes.getDateTimeString());
        
        ORM.table().insert(message);
    }
}
